% Calculate expected bidder and seller surplus
% Using draws from bidder valuation distribution
% For any v0, r, n combination
% Called to precalculate total expected surplus on the platform
% 
% ---------------------------------------------- %
function[Esurbidder,Esurseller,Esurplatform,winbid,highvalsale,reserve,saleprob,Evolume]...
    = EBSsurplus(n,u0,r,cS,cB,Hvalmat,SHvalmat,sims,CDFb,PAR)
            
 % Fix seed for randsample
 s = RandStream('mlfg6331_64');

 % MC Simulations with importance sampling. Precalc in sampleHSHvalues, sample from
 % those values conditional on exceeding rhat.
 HVn     = Hvalmat(n,:);
 SHVn    = SHvalmat(n,:);
 
 % If no reserve, saleprob=1, set r to min value so that also in
 % homogenized value space dont cut off HVNs 
 % Not ideal this code,  
 if r==0
     noreserve = 1;
     r = min(min(SHVn))./(1+cB)-1; 
 else
     noreserve = 0;
 end
 
 if isempty(HVn(HVn>=r*(1+cB)))
     
     saleprob      = 0;
     winbid        = r;
     reserve       = r;
     highvalsale   = max(HVn);
     Esurbidder    = 0;
     Esurseller    = 0;
     Esurplatform  = 0;
     Evolume       = 0;
 
 else
     HV      = randsample(s,HVn(HVn  >= r*(1+cB)),sims,true);
     SHV     = randsample(s,SHVn(HVn >= r*(1+cB)),sims,true);
     v0      = exp(u0);
  
     price        = max(SHV./(1+cB),r);
     if noreserve == 1
        saleprob = 1;
        price        = max(SHV./(1+cB),r);

     else
        saleprob  = (1-CDFb(log(r*(1+cB))).^(n));
     end
     reserve      = r; 
     
     if saleprob > 0
        winbid       = mean(price);
        highvalsale  = mean(HV);
     else
        winbid      = 0;
        highvalsale = 0;
     end
     
     Esurwinbidder = (mean(HV)-mean(price)*(1+cB))*saleprob;
     Esurbidder    = Esurwinbidder/n;                            % Minus cP
     
     %seller commission incorporating minimum amount cS
     Esurseller    = (mean(price)*(1-cS) - v0)*saleprob;         % Minus cL
     Esurplatform  = mean(price)*(cB+cS)*saleprob;               % Plus of course fixed fees cL*T and cP*M and cR*p_r0*T
     Evolume       = mean(price)*saleprob;
     
 end
 
end
